package com.ruoyi.system.service.impl;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import com.ruoyi.system.service.BarcodeService;
import com.ruoyi.system.service.PdfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

@Service
public class PdfServiceImpl implements PdfService {

    @Autowired
    private BarcodeService barcodeService;

    public byte[] generatePdfWithBarcode(String barcodeText) throws Exception {
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);

        document.open();

        // Add title
        Font titleFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 18);
        Paragraph title = new Paragraph("Product Barcode", titleFont);
        title.setAlignment(Element.ALIGN_CENTER);
        document.add(title);

        // Add some space
        document.add(Chunk.NEWLINE);

        for (int i = 0; i < 10; i++) {
            // Generate and add barcode
            BufferedImage barcodeImage = barcodeService.generateBarcodeImage(barcodeText + i);
            Image pdfBarcode = Image.getInstance(barcodeImage, null);
            pdfBarcode.setAlignment(Element.ALIGN_CENTER);
            document.add(pdfBarcode);
            // Add barcode text below
            Font textFont = FontFactory.getFont(FontFactory.HELVETICA, 12);
            Paragraph barcodeTextParagraph = new Paragraph(barcodeText+i, textFont);
            barcodeTextParagraph.setAlignment(Element.ALIGN_CENTER);
            document.add(barcodeTextParagraph);
        }


        document.close();

        return baos.toByteArray();
    }
}
